//
//  CJBrandDetailController.m
//  Boss
//
//  Created by admin on 2018/9/21.
//  Copyright © 2018年 admin. All rights reserved.
//

#import "CJBrandDetailController.h"
#import "CJBrandDetailBottomView.h"
#import <JavaScriptCore/JSContext.h>
#import <JavaScriptCore/JavaScriptCore.h>
#import "UIWebView+TS_JavaScriptContext.h"
#import "CJCommissionController.h"
#import "WYCommentView.h"
#import "CJBrowseListController.h"
#import "CJCommissionShareView.h"
#import "WXApi.h"
@protocol CJBrandDetailDelegate <JSExport>
// AndroidWebView对象调用的JavaScript方法，必须声明！！！
-(void)toCommission:(NSString *)str;
-(void)toComment:(NSString *)str;
-(void)toOnLookers:(NSString *)str;
@end
@interface CJBrandDetailController ()<UIWebViewDelegate,TSWebViewDelegate,CJBrandDetailDelegate,WYCommentViewDelegate,CJBrandDetailBottomViewDelegate,CJCommissionShareViewDelegate>
@property (nonatomic,strong)UIWebView *webView;
@property (nonatomic,strong)CJBrandDetailBottomView *bottomView;
@property (nonatomic,strong)JSContext *context;
@property (nonatomic,strong)WYCommentView *commentView;
@property (nonatomic,strong)NSString *OpportunityId;
@property (nonatomic,strong)NSString *currentCommissionId;
@property (nonatomic,strong)CJCommissionShareView *shareView;
@property (nonatomic,strong)NSString *shareType;
@end

@implementation CJBrandDetailController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setupUI];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"icon_new_business_back"] style:(UIBarButtonItemStyleDone) target:self action:@selector(returnToTop)];
    
    if (@available(iOS 11.0, *)) {
        [self.webView.scrollView setContentInsetAdjustmentBehavior:(UIScrollViewContentInsetAdjustmentNever)];
    } else {
        // Fallback on earlier versions
    }
    
    [self wr_setNavBarBackgroundAlpha:0];
    // Do any additional setup after loading the view.
}
-(void)returnToTop
{
    if ([self.webView canGoBack]) {
        [self.webView goBack];
    }else{
         [self.navigationController popViewControllerAnimated:YES];
    }
    
    
   
}
-(void)setupUI
{
    //self.navigationItem.title = self.navTitle;
    self.webView = [[UIWebView alloc]init];
    self.webView.frame = CGRectMake(0, 0, kScreenWidth, kScreenHeight-50);
    [self.view addSubview:self.webView];
    self.webView.delegate = self;
    WYUserMessage *userMessage = [WYStoreModule currentUserMessage];
    
    NSString *requestString = [NSString stringWithFormat:@"%@%@%@.html?userId=%@",BrandDetail_DOMAIN,@"/business/detail/",self.businessID,userMessage.id];
    
    NSLog(@"%@",requestString);
    
    NSURLRequest *request =[NSURLRequest requestWithURL:[NSURL URLWithString:requestString]];
    NSMutableURLRequest *mutableRequest = [request mutableCopy];
    
    [mutableRequest addValue:[WYStoreModule currentToken] forHTTPHeaderField:@"token"];

    [self.webView loadRequest:mutableRequest];
    
    UIView *bView = [[UIView alloc]init];
    [self.view addSubview:bView];
    [bView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.left.right.mas_equalTo(0);
        make.height.mas_equalTo(self.tabHeight);
    }];
    bView.backgroundColor = [UIColor whiteColor];
    
    
    [bView addSubview:self.bottomView];
    [self.bottomView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.top.mas_equalTo(0);
        make.height.mas_equalTo(50);
        
    }];
    
    
    self.commentView= [[WYCommentView alloc]init];
    self.commentView.delegate = self;
    //    [self.view addSubview:self.maskView];
    //    self.maskView.hidden = YES;
    [self.view addSubview:self.commentView];
    
    [self.commentView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_equalTo(0);
        make.height.mas_equalTo(164);
        make.bottom.mas_equalTo(164);
    }];
    self.commentView.comment.text = @"项目问答";
    self.commentView.textView.placeholder = @"请输入您想咨询的问题";
    //增加监听，当键盘出现或改变时收出消息
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillShow:)
                                                 name:UIKeyboardWillShowNotification
                                               object:nil];
    
    //增加监听，当键退出时收出消息
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillHide:)name:UIKeyboardWillHideNotification
                                               object:nil];
    
    
    
    
    
}
- (void)webView:(UIWebView *)webView didCreateJavaScriptContext:(JSContext *)ctx
{
    ctx[@"commission"] = self;
    ctx[@"comment"] = self;
    ctx[@"onlookers"]=self;
}
-(void)webViewDidFinishLoad:(UIWebView *)webView
{
    
    NSString *price = [self.webView stringByEvaluatingJavaScriptFromString:@"getCommission();"];
    self.shareView.titleLabel.text = [NSString stringWithFormat:@"任何人通过您分享的内容成功阅读您将获得“转发佣金 %@ * 有效点击数”",price];
    
    
    self.currentCommissionId = [self.webView stringByEvaluatingJavaScriptFromString:@"getCommissionId();"];
    [self.bottomView.shareBtn setTitle:[NSString stringWithFormat:@"分享赚%@ x 用户点击量",price] forState:(UIControlStateNormal)];
    NSLog(@"------------------------------%@",price);
    self.context = [self.webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
    self.context [@"commission"] = self;
    self.context [@"comment"]= self;
    self.context [@"onlookers"]=self;
}
-(void)toCommission:(NSString *)str
{
    dispatch_async(dispatch_get_main_queue(), ^{
        // UI更新代码
        //self.showOffBtn.hidden = YES;
        CJCommissionController *ccc = [[CJCommissionController alloc]init];
        ccc.businessId = str;
        [self.navigationController pushViewController:ccc animated:YES];
    });
    
    
    
    
}

-(void)toComment:(NSString *)str
{
    NSLog(@"点击了评论----------------%@",str);
    self.OpportunityId = str;
    dispatch_async(dispatch_get_main_queue(), ^{
        // UI更新代码
        [self.commentView.textView becomeFirstResponder];
    });
}
-(void)toOnLookers:(NSString *)str
{
    dispatch_async(dispatch_get_main_queue(), ^{
        // UI更新代码
        CJBrowseListController *blc =[[CJBrowseListController alloc]init];
        blc.businessId = str;
        [self.navigationController pushViewController:blc animated:YES];
    });
}


#pragma mark commentView
- (void)clickSendButton
{
    if (!self.commentView.textView.text.length) {
        [self toast:@"请输入您想咨询的问题"]; return;
    }
    
    
    [WYHttpServer sendAskWithOpportunityId:self.OpportunityId WithComment:self.commentView.textView.text SucessBlock:^(BOOL success, id response, NSString *errorMessage) {
        if (success) {
            
            
            
        }
    }];
    
    
    
    
    
    
}


- (void)keyboardWillShow:(NSNotification *)aNotification
{
    if (self.commentView.textView.isFirstResponder) {
        NSDictionary *userInfo = [aNotification userInfo];
        NSValue *aValue = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
        CGRect keyboardRect = [aValue CGRectValue];
        CGFloat height = keyboardRect.size.height;
        //self.comment
        
        [self.commentView mas_updateConstraints:^(MASConstraintMaker *make) {
            make.bottom.mas_equalTo(-height);
        }];
        //            self.commentView.frame = CGRectMake(0, kScreenHeight-height, kScreenWidth, 164);
        //
        
        
        
        
        
        //        [self.view addSubview:self.maskView];
        //
        self.maskView.hidden = NO;
    }
    
    
    
    
}
- (void)keyboardWillHide:(NSNotification *)aNotification{
    [self.commentView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.bottom.mas_equalTo(164);
    }];
    //     self.maskView.hidden = YES;
    //    [self.maskView removeFromSuperview];
    //    [self.commentView removeFromSuperview];
}
-(void)didSelectShareAction
{
    
    UIButton *exitBtn = [[UIButton alloc]init];
    exitBtn.frame = CGRectMake(0, 0, kScreenWidth, kScreenHeight);
    [exitBtn addTarget:self action:@selector(exitAction) forControlEvents:(UIControlEventTouchUpInside)];
    [self.maskView addSubview:exitBtn];
    
    [[UIApplication sharedApplication].keyWindow addSubview:self.maskView];
    [[UIApplication sharedApplication].keyWindow addSubview:self.shareView];
    
    
    
    
}
-(void)exitAction
{
    dispatch_async(dispatch_get_main_queue(), ^{
        // UI更新代码
        //self.showOffBtn.hidden = YES;
        [self.maskView removeFromSuperview];
        [self.shareView removeFromSuperview];
    });
    
    
}
-(void)clickWechate
{
    // [self setShareView:nil];
    //    [self.maskView removeFromSuperview];
    //    [self.shareView removeFromSuperview];
    dispatch_async(dispatch_get_main_queue(), ^{
        // UI更新代码
        //self.showOffBtn.hidden = YES;
        [self.maskView removeFromSuperview];
        [self.shareView removeFromSuperview];
    });
    self.shareType = @"1";
    [self showLoading:@""];
    [self loadShareUrl];
    
}
-(void)clickFriend
{
    //   [self setShareView:nil];
    
    dispatch_async(dispatch_get_main_queue(), ^{
        // UI更新代码
        //self.showOffBtn.hidden = YES;
        [self.maskView removeFromSuperview];
        [self.shareView removeFromSuperview];
    });
    
    //    [self.maskView removeFromSuperview];
    //    [self.shareView removeFromSuperview];
    //
    self.shareType = @"2";
    [self showLoading:@""];
    [self loadShareUrl];
    
}

-(void)loadShareUrl
{
    WEAKSELF
    [WYHttpServer getCommissionShareUrlWithBusinessId:self.businessID WithCommissionId:self.currentCommissionId SucessBlock:^(BOOL success, id response, NSString *errorMessage) {
        if (success) {
            dispatch_async(dispatch_get_main_queue(), ^{
                // UI更新代码
                [self hideLoading];
                //self.showOffBtn.hidden = YES;
            });
            UIImageView *imageview = [[UIImageView alloc]init];
            
            [imageview sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@!default",response[@"result"][@"sharePicUrl"]]] completed:^(UIImage * _Nullable image, NSError * _Nullable error, SDImageCacheType cacheType, NSURL * _Nullable imageURL) {
                
                if (self.shareType.integerValue==1) {
                    [weakSelf shareToWechateWithTitle:response[@"result"][@"businessName"] WithMessage:response[@"result"][@"message"] WithImage:image WithLink:response[@"result"][@"shareUrl"]];
                }else{
                    [weakSelf shareToFirendWithTitle:response[@"result"][@"businessName"] WithMessage:response[@"result"][@"message"] WithImage:image WithLink:response[@"result"][@"shareUrl"]];
                }
                
                
                
                
                
                
                
            }];
            
            
            
        }
        
        
        
        
    }];
}

-(void)shareToWechateWithTitle:(NSString *)title WithMessage:(NSString *)message WithImage:(UIImage *)image WithLink:(NSString *)link
{
    
    SendMessageToWXReq *req1 = [[SendMessageToWXReq alloc]init];
    
    // 是否是文档
    req1.bText =  NO;
    
    //    WXSceneSession  = 0,        /**< 聊天界面    */
    //    WXSceneTimeline = 1,        /**< 朋友圈      */
    //    WXSceneFavorite = 2,
    
    
    req1.scene = WXSceneSession;
    
    //创建分享内容对象
    WXMediaMessage *urlMessage = [WXMediaMessage message];
    urlMessage.title = title;//分享标题
    urlMessage.description = message;//分享描述
    [urlMessage setThumbImage:image];//分享图片,使用SDK的setThumbImage方法可压缩图片大小
    
    //创建多媒体对象
    WXWebpageObject *webObj = [WXWebpageObject object];
    webObj.webpageUrl = link;//分享链接
    
    //完成发送对象实例
    urlMessage.mediaObject = webObj;
    req1.message = urlMessage;
    
    //发送分享信息
    BOOL state =  [WXApi sendReq:req1];
    
    if (state) {
        [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"isShare"];
    }
    
    
    
    
}
-(void)shareToFirendWithTitle:(NSString *)title WithMessage:(NSString *)message WithImage:(UIImage *)image WithLink:(NSString *)link
{
    SendMessageToWXReq *req1 = [[SendMessageToWXReq alloc]init];
    
    // 是否是文档
    req1.bText =  NO;
    
    //    WXSceneSession  = 0,        /**< 聊天界面    */
    //    WXSceneTimeline = 1,        /**< 朋友圈      */
    //    WXSceneFavorite = 2,
    
    
    req1.scene = WXSceneTimeline;
    
    //创建分享内容对象
    WXMediaMessage *urlMessage = [WXMediaMessage message];
    urlMessage.title = title;//分享标题
    urlMessage.description = message;//分享描述
    [urlMessage setThumbImage:image];//分享图片,使用SDK的setThumbImage方法可压缩图片大小
    
    //创建多媒体对象
    WXWebpageObject *webObj = [WXWebpageObject object];
    webObj.webpageUrl = link;//分享链接
    
    //完成发送对象实例
    urlMessage.mediaObject = webObj;
    req1.message = urlMessage;
    
    //发送分享信息
    BOOL state =  [WXApi sendReq:req1];
    
    if (state) {
        [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"isShare"];
    }
    
    
    
    
    
}




-(CJCommissionShareView *)shareView
{
    if (!_shareView) {
        _shareView = [CJCommissionShareView sharedShareView];
        _shareView.frame = CGRectMake(0, kScreenHeight-140, kScreenWidth, 140);
        _shareView.delegate = self;
    }
    return _shareView;
    //return []
}

-(CJBrandDetailBottomView *)bottomView
{
    if (!_bottomView) {
        
        _bottomView = [CJBrandDetailBottomView shareedDetailBottonView];
        _bottomView.delegate = self;
    }
    
    
    return _bottomView;
}

@end
